package sel.me.java.learning.redis.learning.lettuce;

import io.lettuce.core.LettuceFutures;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisFuture;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import io.lettuce.core.resource.ClientResources;
import org.apache.commons.lang3.time.StopWatch;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author shenenlu 2020年12月23日 下午15:35:39
 */
public class LettucePipeline {
    public static void main(String[] args) {
        LettucePipeline lettucePipeline = new LettucePipeline();
        lettucePipeline.testPipeline();
    }


    public void testPipeline(){
        RedisClient client = RedisClient.create(ClientResources.create(),
                RedisURI.create("redis://123456@127.0.0.1:6379/0"));
        StatefulRedisConnection<String, String> connection = client.connect();
        StopWatch stopwatch = StopWatch.createStarted();
        RedisAsyncCommands<String, String> commands = connection.async();
        // disable auto-flushing
        commands.setAutoFlushCommands(false);
        // perform a series of independent calls
        List<RedisFuture<?>> futures = new ArrayList<>();
        for (int i = 1;i < 50; i++) {
            futures.add(commands.set("mmm"+i,"value-" + i));
            futures.add(commands.expire("mmm"+ i, 3600));
        }

        // write all commands to the transport layer
        // 真正地flush操作
        commands.flushCommands();
        // synchronization example: Wait until all futures complete
        boolean result = LettuceFutures.awaitAll(5, TimeUnit.SECONDS,
                futures.toArray(new RedisFuture[futures.size()]));
        stopwatch.stop();
        System.out.println("--------------耗时----" + stopwatch.getTime(TimeUnit.MILLISECONDS));
        // later
        connection.close();
        client.shutdown();
    }
}
